import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'


// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})




// request interceptor
service.interceptors.request.use(
  config => {
    var lang =  localStorage.getItem("lang");
    if(lang==null){
      localStorage.setItem("lang" , 'zh-CN');
    }
    config.headers['Lang'] = lang=='zh-CN'?1:2
    config.data.token =  localStorage.getItem("token")?localStorage.getItem("token"):'';
    return config
  },

  error => {
    // 报错信息
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 200) {
      // code!=0 接扣报错
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 1000
      })
      if(res.code == '-99'){
        // token 过期
        localStorage.setItem("token" , '')
        router.push({path:'/login'})
        return Promise.reject(new Error(res.msg || 'Error'))
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
    })
    return Promise.reject(error.message)
  }
)

export default service
